package com.exp.controller;

import com.baidu.aip.face.AipFace;
import com.exp.dto.FaceDTO;
import com.exp.pojo.UserInf;
import com.exp.properties.FaceProperties;
import com.exp.result.Result;
import com.exp.result.StatusCode;
import com.exp.service.UserInfService;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.UUID;

/**
 * 人脸识别模块-why
 */
@RestController
@RequestMapping("/admin/facekeyInf")
@Slf4j
public class FacekeyInfController {
    @Autowired
    private FaceProperties faceProperties;
    @Autowired
    private UserInfService userInfService;
    /*
     * 人脸注册
     * 输入：摄像头、人脸
     * */

    @PostMapping("/faceReg")
    public Result faceReg(@RequestBody FaceDTO faceDTO) throws Exception {
        log.info("人脸注册开启~~~~·");
        System.out.println(faceDTO);
        AipFace client = null;
        try {
            client = new AipFace(faceProperties.getAppId(), faceProperties.getApiKey(), faceProperties.getSecretKey());
            client.setConnectionTimeoutInMillis(5000); // 5秒
            client.setSocketTimeoutInMillis(60000); // 60秒

            HashMap<String, String> options = new HashMap<>();
            options.put("action_type", "REPLACE");

            String base64ImageStr = faceDTO.getFile();
            System.out.println("-------"+base64ImageStr);
            String imageType = "BASE64";
            String groupId = "test";

            String faceUrl = saveFaceImage(base64ImageStr);
            String facePath = getFaceImagePath(base64ImageStr);

            UserInf userInf = userInfService.getByUserId(faceDTO.getId());
            userInf.setFaceurl(faceDTO.getId().toString());
            userInf.setFacepath(facePath);
            System.out.println("id:" + faceDTO.getId() + " -- " + userInf);
            if (userInf != null)
                userInfService.updateById(userInf);
            System.out.println("userInf更新后:" + userInf);

            String userInfo = "{\"faceUrl\":\"" + faceUrl + "\",\"facePath\":\"" + facePath + "\"}";

            options.put("user_info", userInfo);

            String userId = faceDTO.getId().toString(); // 使用数据库生成的ID作为userId

            System.out.println(userId);

            //去掉 data 头
            String base64String = base64ImageStr.split(",")[1];

            JSONObject res = client.addUser(base64String, imageType, groupId, userId, options);
            System.out.println(res.toString(2));
            return Result.success(StatusCode.SUCCESS, "注册成功", res.toString(2));

        } catch (Exception e) {
            log.error("注册失败", e.getMessage(), e);
            throw new Exception("注册失败");
        }
    }

    private String saveFaceImage(String base64ImageStr) {
        if (base64ImageStr == null || base64ImageStr.isEmpty()) {
            return null;
        }

        String directoryPath = "src/main/resources/images/";

        String mimePart = base64ImageStr.split(";")[0].split(":")[1].trim();
        String uuid = UUID.randomUUID().toString();
        String fileName = mimePart.split("/")[1] + uuid + "." + mimePart.split("/")[1];
        String filePath = directoryPath + fileName;

        try {
            File directory = new File(directoryPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            byte[] imageBytes = Base64.getDecoder().decode(base64ImageStr.split(",")[1]);
            Files.write(Paths.get(filePath), imageBytes);

            String fileUrl = "/images/" + fileName;
            return fileUrl;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private String getFaceImagePath(String base64ImageStr) {
        if (base64ImageStr == null || base64ImageStr.isEmpty()) {
            return null;
        }

        String directoryPath = "src/main/resources/images/";

        String mimeType = base64ImageStr.substring(base64ImageStr.indexOf("data:") + 5, base64ImageStr.indexOf(";")).split(";")[0];
        String extension = getExtensionFromMimeType(mimeType);

        String uniqueFileName = UUID.randomUUID().toString() + extension;
        String filePath = directoryPath + uniqueFileName;

        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }

        return filePath;
    }

    private String getExtensionFromMimeType(String mimeType) {
        if (mimeType.startsWith("image/png")) {
            return ".png";
        } else if (mimeType.startsWith("image/jpeg")) {
            return ".jpg";
        } else if (mimeType.startsWith("image/gif")) {
            return ".gif";
        } else {
            return ".png";
        }
    }

}
